<?php

/*
	[Discuz!] (C)2001-2007 Comsenz Inc.
	This is NOT a freeware, use is subject to license terms

	$RCSfile: viewthread.php,v $
	$Revision: 1.166.2.13 $
	$Date: 2007/05/14 13:32:08 $
*/
define('CURSCRIPT', 'viewthread');
define('SQL_ADD_THREAD', ' t.dateline, t.special, t.lastpost AS lastthreadpost,');

require_once './include/common.inc.php';
require_once DISCUZ_ROOT.'./include/forum.func.php';
supe_dbconnect();


$page = max(1, intval($page));

if($cachethreadlife && $forum['threadcaches'] && !$discuz_uid && $page == 1 && !$forum['special']) {

	$forum['livedays'] = ceil(($timestamp - $forum['dateline']) / 86400);
	$forum['lastpostdays'] = ceil(($timestamp - $forum['lastthreadpost']) / 86400);

	$threadcachemark = 100 - (
		$forum['displayorder'] * 15 +
		$forum['digest'] * 10 +
		min($forum['views'] / max($forum['livedays'], 10) * 2, 50) +
		max(-10, (15 - $forum['lastpostdays'])) +
		min($forum['replies'] / $_DCACHE['settings']['postperpage'] * 1.5, 15));

	if($threadcachemark < $forum['threadcaches']) {

		$threadcache = getcacheinfo($tid);

		if($timestamp - $threadcache['filemtime'] > $cachethreadlife) {
			@unlink($threadcache['filename']);
			define('CACHE_FILE', $threadcache['filename']);

		} else {
			readfile($threadcache['filename']);

			$supe_pushstatusadd = '';
			viewthread_updateviews();

			$debug && debuginfo();
			die('<script type="text/javascript">document.getElementById("debuginfo").innerHTML = " '.($debug ? 'Update at '.gmdate("H:i:s", $threadcache['filemtime'] + 3600 * 8).', Processed in '.$debuginfo['time'].' second(s), '.$debuginfo['queries'].' Queries'.($gzipcompress ? ', Gzip enabled' : '') : '').'";</script>');
		}
	}
}

require_once DISCUZ_ROOT.'./include/discuzcode.func.php';

$discuz_action = 3;

$query = $db->query("SELECT * FROM {$tablepre}threads t WHERE tid='$tid' AND displayorder>='0'");

$lastmod = array();

if(!$thread = $db->fetch_array($query)) {

	$tid = $_GET['tid'];
	if(is_numeric($tid) && $supe['status'] && !empty($supe_fromsupesite) && md5("$discuz_auth_key-$tid") == $supe_fromsupesite) {
		supe_dbconnect();
		$supe['db']->query("UPDATE {$supe[tablepre]}spaceitems SET tid='0' WHERE tid='$tid'");
	}

	wapshowmessage('thread_nonexistence');

}

$supe_fromdiscuz = $supe['status'] && $thread['itemid'] ? md5("$discuz_auth_key-$thread[itemid]") : '';
$iscircle = $supe['status'] && $supe['circlestatus'] && $forum['status'] == 2 && $thread['sgid'];

$codecount = 0;
$thread['subjectenc'] = rawurlencode($thread['subject']);
$fromuid = $creditspolicy['promotion_visit'] && $discuz_uid ? '&amp;fromuid='.$discuz_uid : '';

$oldtopics = isset($_DCOOKIE['oldtopics']) ? $_DCOOKIE['oldtopics'] : 'D';
if(strpos($oldtopics, 'D'.$tid.'D') === FALSE) {
	$oldtopics = 'D'.$tid.$oldtopics;
	if(strlen($oldtopics) > 3072) {
		$oldtopics = preg_replace("((D\d+)+D).*$", "\\1", substr($oldtopics, 0, 3072));
	}
	dsetcookie('oldtopics', $oldtopics, 3600);
}

if($lastvisit < $thread['lastpost'] && (!isset($_DCOOKIE['fid'.$fid]) || $thread['lastpost'] > $_DCOOKIE['fid'.$fid])) {
	dsetcookie('fid'.$fid, $thread['lastpost'], 3600);
}
$navigation = '&raquo; '.$forum['name'].' &raquo; '.$thread['subject'];
$navtitle = $thread['subject'];
if($forum['type'] == 'sub') {
	$query = $db->query("SELECT fid, name FROM {$tablepre}forums WHERE fid='$forum[fup]'");
	$fup = $db->fetch_array($query);
	$navigation = '&raquo; <a href="'.($iscircle ? $supe['siteurl'].'?action_mygroup_gid_'.$thread['sgid'].'_op_list_type_bbs_fid_'.$fup[fid] : 'forumdisplay.php?fid='.$fup[fid]).'">'.$fup[name].'</a> '.$navigation;
	$navtitle = $navtitle.' - '.strip_tags($fup['name']);
}
$navtitle .= ' - ';

if($thread['typeid'] && isset($forum['threadtypes']['types'][$thread['typeid']])) {
	$thread['subject'] = ($forum['threadtypes']['listable'] ? '<a href="forumdisplay.php?fid='.$fid.'&amp;filter=type&amp;typeid='.$thread['typeid'].'">['.$forum['threadtypes']['types'][$thread['typeid']].']</a>' : '['.$forum['threadtypes']['types'][$thread['typeid']].']').' '.$thread['subject'];
}
if(empty($forum['allowview'])) {
	if(!$forum['viewperm'] && !$readaccess) {
		wapshowmessage('group_nopermission', NULL, 'NOPERM');
	} elseif($forum['viewperm'] && !forumperm($forum['viewperm'])) {
		$navtitle = '';
		wapshowmessage('forum_nopermission', NULL, 'NOPERM');
	}
}

if($forum['password'] && $forum['password'] != $_DCOOKIE['fidpw'.$fid]) {
	dheader("Location: {$boardurl}forumdisplay.php?fid=$fid&amp;sid=$sid");
}

if($thread['readperm'] && $thread['readperm'] > $readaccess && !$forum['ismoderator'] && $thread['authorid'] != $discuz_uid) {
	wapshowmessage('thread_nopermission', NULL, 'NOPERM');
}

$raterange = $modratelimit && $adminid == 3 && !$forum['ismoderator'] ? array() : $raterange;

$extra = rawurlencode($extra);

$allowgetattach = !empty($forum['allowgetattach']) || ($allowgetattach && !$forum['getattachperm']) || forumperm($forum['getattachperm']);

$postlist = array();
$attachpids = $announcepm = 0;
if(empty($action) && $tid) {

	$showsettings = str_pad(decbin($showsettings), 3, '0', STR_PAD_LEFT);

	$customshow = $discuz_uid ? str_pad(base_convert($customshow, 10, 3), 3, '0', STR_PAD_LEFT) : '222';

	$showsignatures = $customshow{0} == 2 ? $showsettings{0} : $customshow{0};
	$showavatars = $customshow{1} == 2 ? $showsettings{1} : $customshow{1};
	$showimages = $customshow{2} == 2 ? $showsettings{2} : $customshow{2};
	$allowpaytoauthor = $forum['allowpaytoauthor'];

	$ppp = M_PER_PAGE;

	$totalpage = ceil(($thread['replies'] + 1) / $ppp);
	$page > $totalpage && $page = $totalpage;

	$pagebydesc = $page > 50 && $page > ($totalpage / 2) ? TRUE : FALSE;

	if($pagebydesc) {
		$firstpagesize = ($thread['replies'] + 1) % $ppp;
		$ppp2 = $page == $totalpage && $firstpagesize ? $firstpagesize : $ppp;
		$realpage = $totalpage - $page + 1;
		$start_limit = max(0, ($realpage - 2) * $ppp + $firstpagesize);
		$numpost = ($page - 1) * $ppp;
		$pageadd =  "ORDER BY dateline DESC LIMIT $start_limit, $ppp2";
	} else {
		$start_limit = $numpost = ($page - 1) * $ppp;
		if($start_limit > $thread['replies']) {
			$start_limit = $numpost = 0;
			$page = 1;
		}
		$pageadd =  "ORDER BY dateline LIMIT $start_limit, $ppp";
	}
	
	$multipage = now_wap_multi($thread['replies'] + 1, $ppp, $page, "{$boardurl}t/$tid/$p_page/", $threadcount);

	if($thread['special'] > 0) {
		include_once DISCUZ_ROOT.'./include/special.inc.php';
	}

	$extcredits_thread = array();

	if(!empty($extcredits)) {
		foreach($extcredits as $key => $value) {
			if($value['showinthread']) {
				$extcredits_thread['extcredits'.$key] = array('title' => $value['title'], 'unit' => $value['unit']);
			}
		}
	}

	$fieldsadd = '';
	if(is_array($_DCACHE['fields_thread'])) {
		foreach($_DCACHE['fields_thread'] as $field) {
			$fieldsadd .= ', mf.field_'.$field['fieldid'];
		}
	}

	$newpostanchor = $postcount = $ratelogpids = 0;

	$onlineauthors = array();
	$query = $db->query("SELECT p.*, m.uid, m.username, m.groupid, m.adminid, m.regdate, m.lastactivity, m.posts,
		m.pageviews, m.credits, m.extcredits1, m.extcredits2, m.extcredits3, m.extcredits4, m.extcredits5, m.extcredits6,
		m.extcredits7, m.extcredits8, m.invisible $fieldsadd
		FROM {$tablepre}posts p
		LEFT JOIN {$tablepre}members m ON m.uid=p.authorid
		WHERE p.tid='$tid' AND p.invisible='0' $pageadd");

	while($post = $db->fetch_array($query)) {

		if(!$newpostanchor && $post['dateline'] > $lastvisit) {
			$post['newpostanchor'] = '<a name="newpost"></a>';
			$newpostanchor = 1;
		} else {
			$post['newpostanchor'] = '';
		}
		$post['lastpostanchor'] = $numpost == $thread['replies'] ? '<a name="lastpost"></a>' : '';

		if($pagebydesc) {
			$post['number'] = $numpost + $ppp2--;
		} else {
			$post['number'] = ++$numpost -1;
		}
		$post['count'] = $postcount++;
		$post['dbdateline'] = $post['dateline'];
		$post['dateline'] = gmdate("$dateformat $timeformat", $post['dateline'] + $timeoffset * 3600);
		$post['groupid'] = $_DCACHE['usergroups'][$post['groupid']] ? $post['groupid'] : 7;

		if($post['username']) {
			$onlineauthors[] = $post['authorid'];
			$post['groupid'] = getgroupid($post['authorid'], $_DCACHE['usergroups'][$post['groupid']], $post);
			$post['readaccess'] = $_DCACHE['usergroups'][$post['groupid']]['readaccess'];
			if($userstatusby == 1 || $_DCACHE['usergroups'][$post['groupid']]['byrank'] === '0') {
				$post['authortitle'] = $_DCACHE['usergroups'][$post['groupid']]['grouptitle'];
				$post['stars'] = $_DCACHE['usergroups'][$post['groupid']]['stars'];
			} elseif($userstatusby == 2) {
				foreach($_DCACHE['ranks'] as $rank) {
					if($post['posts'] > $rank['postshigher']) {
						$post['authortitle'] = $rank['ranktitle'];
						$post['stars'] = $rank['stars'];
						break;
					}
				}
			}
			$post['authoras'] = !$post['anonymous'] ? ' '.addslashes($post['author']) : '';
			$post['regdate'] = gmdate($dateformat, $post['regdate'] + $timeoffset * 3600);
			$post['allowuseblog'] = $_DCACHE['usergroups'][$post['groupid']]['allowuseblog'];

		} else {

			if(!$post['authorid']) {
				$post['useip'] = substr($post['useip'], 0, strrpos($post['useip'], '.')).'.x';
			}

		}

		if($ratelogrecord && $post['ratetimes']) $ratelogpids .= ','.$post['pid'];

		$forum['allowbbcode'] = $forum['allowbbcode'] ? ($_DCACHE['usergroups'][$post['groupid']]['allowcusbbcode'] ? 2 : 1) : 0;

		$post['ratings'] = karmaimg($post['rate'], $post['ratetimes']);
		$post['message'] = discuzcode($post['message'], 1, $post['bbcodeoff'], $post['htmlon'], 0, $forum['allowbbcode'], (0 && $showimages ? 1 : 0), $forum['allowhtml'], ($forum['jammer'] && $post['authorid'] != $discuz_uid ? 1 : 0), 0, $post['authorid']);
		$post['signature'] = $post['usesig'] ? $post['signature'] : '';
		$postlist[$post['pid']] = $post;
	}

	if(empty($postlist)) {
		wapshowmessage('undefined_action', NULL, 'HALTED');
	}


	$usesigcheck = $discuz_uid && $sigstatus ? 'checked' : '';
	$allowpostreply = ((!$thread['closed'] && !checkautoclose()) || $forum['ismoderator']) && ((!$forum['replyperm'] && $allowreply) || ($forum['replyperm'] && forumperm($forum['replyperm'])) || $forum['allowreply']);
	$allowpost = (!$forum['postperm'] && $allowpost) || ($forum['postperm'] && forumperm($forum['postperm'])) || $forum['allowpost'];

	if($allowpost) {
		$allowpostpoll = $allowpostpoll && ($forum['allowpostspecial'] & 1);
		$allowposttrade = $allowposttrade && ($forum['allowpostspecial'] & 2);
		$allowpostreward = $allowpostreward && ($forum['allowpostspecial'] & 4) && isset($extcredits[$creditstrans]);
		$allowpostactivity = $allowpostactivity && ($forum['allowpostspecial'] & 8);
	} else {
		$allowpostpoll = $allowposttrade = $allowpostreward = $allowpostactivity = FALSE;
	}

	viewthread_updateviews();

	include template($iscircle && empty($frombbs) ? 'supesite_viewthread' : 'mobile_view');

}

function viewthread_updateviews() {
	global $delayviewcount, $supe_pushstatusadd, $timestamp, $tablepre, $tid, $db, $adminid;

	if(($delayviewcount == 1 || $delayviewcount == 3) && !$supe_pushstatusadd) {
		$logfile = './forumdata/cache/cache_threadviews.log';
		if(substr($timestamp, -2) == '00') {
			require_once DISCUZ_ROOT.'./include/misc.func.php';
			updateviews('threads', 'tid', 'views', $logfile);
		}
		if(@$fp = fopen(DISCUZ_ROOT.$logfile, 'a')) {
			fwrite($fp, "$tid\n");
			fclose($fp);
		} elseif($adminid == 1) {
			showmessage('view_log_invalid');
		}
	} else {
		$db->query("UPDATE {$tablepre}threads SET views=views+1 $supe_pushstatusadd WHERE tid='$tid'", 'UNBUFFERED');
	}
	unset($supe_pushstatusadd);
}

?>